package com.example.yingjiguanli_demo.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.yingjiguanli_demo.pojo.UserRoleDTO;
import com.example.yingjiguanli_demo.pojo.Users;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface UsersMapper extends BaseMapper<Users> {
    /**
     * 根据用户名查询用户
     * @param username 用户名
     * @return Users
     */
    @Select("select * from users where username = #{username}")
    Users findByUsername(String username);

    /**
     * 插入用户
     * @param user 用户
     * @return int
     */
    @Insert("INSERT INTO users (username, password, email, m_name,status) VALUES (#{username}, #{password}, #{email}, #{mName}, #{status})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insertUser(Users user);

    /***
     * 查询所有用户角色信息
     * @return List<UserRoleDTO>
     */
    @Select("SELECT u.id AS userId, u.username, u.email, r.role_name, u.created_at, u.u_name, u.status, u.id, " +
            "GROUP_CONCAT(r.role_name) AS permissions " +   // 聚合角色名到 permissions 字段
            "FROM users u " +
            "LEFT JOIN user_roles ur ON u.id = ur.user_id " +
            "LEFT JOIN roles r ON ur.role_id = r.id " +
            "GROUP BY u.id")  // 确保按用户 ID 分组
    List<UserRoleDTO> getAllUsersWithRoles();

    /***
     * 根据用户id查询用户角色信息
     * @param userId 用户id
     * @return UserRoleDTO
     */
    @Select("SELECT u.id AS userId, u.username, u.email, u.u_name, u.created_at, u.status, u.id, " +
            "GROUP_CONCAT(r.role_name) AS permissions " +   // 聚合角色名到 permissions 字段
            "FROM users u " +
            "LEFT JOIN user_roles ur ON u.id = ur.user_id " +
            "LEFT JOIN roles r ON ur.role_id = r.id " +
            "WHERE u.id = #{userId} " +  // 按用户 ID 查询
            "GROUP BY u.id")  // 确保按用户 ID 分组
    UserRoleDTO getUserById(Long userId);



}
